package com.ygqh.baby.handler;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.PromotionType;
import com.ygqh.baby.ao.YgQuartzJob;
import com.ygqh.baby.model.PromotionTag;
import com.ygqh.baby.service.ScheduleJobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.*;

/**
 * 〈〉
 *
 * @author guohao
 * @date 2019/3/8 14:20
 * @since 1.0.0
 */
@Component
public class DefaultPromotionTagHandler {

    @Autowired
    private PackPromotionTagHandler packPromotionTagHandler;

    @Autowired
    private ScheduleJobService scheduleJobService;

    private static ExecutorService executorService;

    @PostConstruct
    public void init() {
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("PackPromotionTagHandler.updatePromotionTag-pool-%d").build();
        executorService = new ThreadPoolExecutor(5, 5,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
    }

    public AbstractProductPromotionTagHandler getPromotionTagHandler(PromotionType promotionType) {
        if (PromotionType.Pack.equals(promotionType)) {
            return packPromotionTagHandler;
        }
        return null;

    }

    public void updatePromotionTag(Long relateId, PromotionType promotionType, List<Long> addList, List<Long> deleteList, Boolean addJob) {

        executorService.execute(() -> {
            AbstractProductPromotionTagHandler promotionTagHandler = getPromotionTagHandler(promotionType);
            Message message = promotionTagHandler.updatePromotionTag(relateId, addList, deleteList);
            if (addJob) {
                PromotionTag promotionTag = (PromotionTag) message.getExtra();
                if (promotionTag.isExpired()) {
                    scheduleJobService.deleteJob(promotionTag.getJobName(), YgQuartzJob.PromotionTag.name(), promotionTag.getUpdateBy());
                    return;
                }
                scheduleJobService.updatePromotionTag(relateId, promotionTag);
            }
        });
    }
}
